package web;


import dao.FileDao;
import utils.FileDownLoad;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.sql.SQLException;
import java.util.Collection;

@WebServlet("/uploadFiles")
@MultipartConfig(location = "F:\\kaifamiao.1\\JavaWeb\\temp\\upload")
public class UploadFilesServet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        Collection<Part> parts = req.getParts();
        File dir = new File("F:\\kaifamiao.1\\JavaWeb\\temp\\upload");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String message = "";
        String download = "";
        String html = "<html><body>";
        for (Part part : parts){
            String type = part.getContentType();
            String name = part.getSubmittedFileName();
            String fileName = dir + File.separator + name;
            File file = new File(fileName);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            //获取本地主机IP
            String localAddr = req.getLocalAddr();
            //获取客户端主机IP
            String remoteHost = req.getRemoteHost();
            //获取本机Servlet服务端口
            int port = req.getLocalPort();
            //获取上下文路径
            String contextPath = req.getContextPath();
            //获取文件大小
            long partSize = part.getSize();
            //获取上传时间
            long timestamp = System.currentTimeMillis();
            String data = FileDownLoad.getData(timestamp);
            //获取下载地址
            String address = "http://" + "10.0.3.145" + ":" +port + contextPath + "/download?file=" + name;
            try {
                FileDao.addSql(name, partSize,remoteHost,address);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            part.write(fileName);
            message += "<span>" + name + "上传成功</span> <br>";
        }
        html += message;
        html += download;
        html += "</body></html>";
        resp.getWriter().write(html);
    }
}
